package com.julian.delegatePattern.virtualProxy;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class ImageUnloaded implements State {

    ImageProxyState imageProxyState;

    public ImageUnloaded(ImageProxyState imageProxyState) {
        this.imageProxyState = imageProxyState;
    }


    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.drawString("Loading CD Cover, please wait...",x+ 300, y + 190);
        if (!imageProxyState.isRetrieving()){
            imageProxyState.setRetrieving(true);
            //open a sub-Thread to load photo
            Thread retrievalThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        ImageIcon imageIcon = new ImageIcon(imageProxyState.getImageURL(),"CD Cover");
                        imageProxyState.setImageIcon(imageIcon);
                        c.repaint();//repaint(0, 0, 0, width, height);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            imageProxyState.setRetrievalThread(retrievalThread);
            imageProxyState.startThread();
        }
        imageProxyState.setCurrentState(imageProxyState.imageLoaded);
    }

    @Override
    public int getIconWidth() {
        return 800;
    }

    @Override
    public int getIconHeight() {
        return 600;
    }
}
